package com.mygdx.game.desktop.demo;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.ParticleEffectPool;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ParticleEffectsTestGame extends Game {

    private Stage stage;
    private SpriteBatch batch;
    private ParticleEffect effect;  //粒子效果类
    private ParticleEffectPool particlepool;    // 粒子特效池
    private ParticleEffect tempEffect;
    private List<ParticleEffect> particlelist;

    private int pointX = 1;
    private int PointY = 2;

    @Override
    public void create() {

        stage = new Stage();
        batch = new SpriteBatch();
        particlelist = new ArrayList<>();
        effect = new ParticleEffect();//初始化粒子效果类
        // 加载粒子编辑器类文件
        // 第二个参数为相对路径
        effect.load(Gdx.files.internal("effect/test.p"), Gdx.files.internal("effect"));
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();
        effect.setPosition(w / 2, h / 2);
        // 初始化粒子特效池
        particlepool = new ParticleEffectPool(effect, 2, 5);
    }

    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        tempEffect = particlepool.obtain();
        // 特效位置跟随鼠标
        tempEffect.setPosition(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
        // 判断 如果鼠标点位有移动 就新增特效点
        if (pointX != Gdx.input.getX() || PointY != Gdx.graphics.getHeight() - Gdx.input.getY())
            particlelist.add(tempEffect);
        pointX = Gdx.input.getX();
        PointY = Gdx.graphics.getHeight() - Gdx.input.getY();
        batch.begin();

        for (int i = 0; i < particlelist.size(); i++) {
            if (particlelist.size() >= 50){
                particlelist.remove(0);
            }else{
                particlelist.get(i).draw(batch, Gdx.graphics.getDeltaTime());
            }
        }

        //effect.draw(batch, Gdx.graphics.getDeltaTime());//绘制粒子效果

        batch.end();

    }

    public void dispose() {
        particlepool.clear();
    }

    public static void main(String[] args) {
        new LwjglApplication(new ParticleEffectsTestGame());
    }

}
